/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package staplers;

import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.NamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpSession;

/**
 *
 * @author robert
 */
@ManagedBean
@SessionScoped
public class UserCTRL {
    DBHelper helper;
    User user;
    private String  errMsg,
                    user2Search;
    boolean emptyUser = true;
    private DataModel userList;
    private boolean viewingSearchResults;
    private List priorOrders;

    /** Creates a new instance of UserCTRL */
    public UserCTRL() {
        helper = new DBHelper();
    }

    public DBHelper getHelper() {
        return helper;
    }

    public boolean isViewingSearchResults() {
        return viewingSearchResults;
    }

    public List getPriorOrders() {
        if (priorOrders == null)
            priorOrders = helper.getPriorOrdersByUser(user);
        return priorOrders;
    }

    
    
    public String getUser2Search() {
        return user2Search;
    }

    public void setUser2Search(String user2Search) {
        this.user2Search = user2Search;
    }
    
    public boolean isEmptyUser() {
        return emptyUser;
    }

    public void setEmptyUser(boolean emptyUser) {
        this.emptyUser = emptyUser;
    }
    
    public String getErrMsg() {
        String temp = errMsg;
        errMsg = null;
        return temp;
    }
    
    public User getUser()
    {
        return user;
    }
    
    public String login()
    {
        errMsg = "";
        FacesContext ctx = FacesContext.getCurrentInstance();

        Map<String, String> request = ctx.getExternalContext().getRequestParameterMap();
        String login = request.get("loginForm" + NamingContainer.SEPARATOR_CHAR + "login");
        String password = request.get("loginForm" + NamingContainer.SEPARATOR_CHAR + "password");
        user = helper.login(login, password);
        if (user == null) {
            errMsg = "Wrong username or pass";
            return "Login";
        }
        
        emptyUser = false;
        
        if (user.getIsAdmin())
            return "AdminHome";
        else
        {
            if (((CartCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("cartCTRL"))!=null)
                ((CartCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("cartCTRL")).createOrder(user);
            return "CustomerMain";
        }            
    }
    
    public String logout()
    {
        user = null;
        emptyUser = true;
        HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        session.invalidate();
        return "index";
    }
    
    public String registerPrep()
    {
        user = new User();
        emptyUser = true;
        return "register";
    }
    
    public String register()
    {
        errMsg = "";
        
        int retValue = helper.register(user);
        if (retValue == -1) {
            user = null;
            errMsg = "Error: User name already taken";
            return "Register";
        }
        
        emptyUser = false;
        return "CustomerMain";        
    }
    
    public String updateUser()
    {
        errMsg = "";
                
        int retValue = helper.updateUser(user);
        
        if (retValue == -1)
        {
            errMsg = "Hibernate error... Try again please!";
            return "ClientAccountDetails";
        }
        
        this.setErrMsg("User updated");
        return "CustomerMain";
    }
    
    public String deleteUser()
    {
        errMsg = "";
        int retValue = helper.deleteUser(user);
        
        if (retValue == -1)
        {
            errMsg = "Uh oh... something bad happened";
            return "ClientAccountDetails";
        }
        
        user = null;
        
        errMsg = "Account deletion successful";
        return "login";
    }
    
    
    public String cancel()
    {
        if (user == null || emptyUser)
            return "index";
            
        if (user.getIsAdmin())
            return "AdminHome";
        else
            return "CustomerMain";
    }
    
    public DataModel getUserList()
    {
        if (userList == null)
            userList = new ListDataModel(helper.getUserList());
        return userList;
    }
    
    public String manageAccountsPrep()
    {
        userList = null;
        viewingSearchResults = false;
        return "ManageAccounts";
    }
        
    public String promoteUser()
    {
        if (!user.getIsAdmin())
        {
            this.setErrMsg("You are not admin!");
            return "CustomerMain";
        }
        User user = (User)userList.getRowData();
        if (user.getIsAdmin())
        {
            setErrMsg("Cannot promote admin");
            return "ManageAccounts";
        }
        
        user.setIsAdmin(true);
        helper.updateUser(user);
        this.setErrMsg("User promoted");
        return "AdminHome";
    }
    
    public String demoteUser()
    {
        if (!user.getIsAdmin())
        {
            this.setErrMsg("You are not admin!");
            return "CustomerMain";
        }
        User user = (User)userList.getRowData();
        if (!user.getIsAdmin())
        {
            this.setErrMsg("Cannot demote customer");
            return "ManageAccounts";
        }
        user.setIsAdmin(false);
        helper.updateUser(user);
        this.setErrMsg("User demoted");
        return "AdminHome";
    }

    public String deleteAnotherUser()
    {
        if (!user.getIsAdmin())
        {
            this.setErrMsg("You are not admin!");
            return "CustomerMain";
        }
        User user = (User)userList.getRowData();
        helper.deleteUser(user);
        this.setErrMsg("User deleted");
        return "AdminHome";
    }
    
    public void setErrMsg(String string) {
        this.errMsg = string;
    }
    
    public String search()
    {
        List list = helper.searchUsers(user2Search);
        if (list == null)
            this.setErrMsg("No users found!");
        userList = new ListDataModel(list);
        this.viewingSearchResults = true;
        return "ManageAccounts";
    }
    
    public String getPastOrders()
    {
        priorOrders = null;
        return "OrderHistory";
    }
}
